package pl.hexar.action.offert;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.Transactional;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.framework.EntityHome;
import org.jboss.seam.security.Identity;

import pl.hexar.model.Offert;
import pl.hexar.model.User;

@Name("offertHome")
public class OffertHome extends EntityHome<Offert>
{

	private static final long serialVersionUID = 4759626757779481301L;
	
	@RequestParameter Long offertId;
	@In
	EntityManager entityManager;
	@In
	Identity identity;
	
	@In 
	LastOffert lastOffert;

    @Override
    public Object getId()
    {
        if (offertId == null)
        {
            return super.getId();
        }
        else
        {
            return offertId;
        }
    }

    @Override @Begin
    public void create() {
        super.create();
    }
    @Override
	@Transactional
    public String persist() {
    	
    	    	
    	Query findUser = entityManager.createNamedQuery("User.findByLogin");
    	findUser.setParameter("login", identity.getCredentials().getUsername());
    	User user = (User) findUser.getSingleResult();
    	
    //	user.getOferts().add(getInstance());
    	getInstance().setUser(user);
    	getInstance().setCreationDate(new Date());
    	getInstance().setModDate(new Date());
    	 
    	String persist = super.persist();
    	lastOffert.refresh();
    	return persist;
    }


}
